
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  ProductInStockGetProductCategoriesName,
  ProductInStockGetProductCategoryNums,
  ProductInStockCreate
} from "@/api/stu/SupplyChainFinance"
import * as echarts from 'echarts';
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useSupplierWarehouse() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const dataList2 = ref<any>([]);
  const loading2 = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const AddVisible = ref<boolean>(false);
  const RefStubimAddFrom = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "产品名称",
      prop: "supplyName",
    }, {
      label: "型号",
      prop: "supplyName",
    }, {
      label: "动库类型（出库）",
      prop: "supplyName",
    }, {
      label: "数量",
      prop: "supplyName",
    }, {
      label: "金额",
      prop: "supplyName",
    }, {
      label: "日期",
      prop: "supplyName",
    }
  ]
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "电商企业",
      prop: "supplyName",
    }, {
      label: "商品信息",
      prop: "supplyName",
    }, {
      label: "状态",
      prop: "supplyName",
    }, {
      label: "数量",
      prop: "supplyName",
    }, {
      label: "金额",
      prop: "supplyName",
    },
    {
      label: "状态",
      prop: "netCashFlowGrowth",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isActive ? "success" : ""}>
          {
            row.isActive ? "已锁定" : "未锁定"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ]
  const AddSelete = ref([]);
  const rules: any = {
    name: [
      { required: true, message: "请选择产品名称", trigger: 'blur' }
    ],
    num: [
      {
        required: true,
        validator: (rule: any, value: number, callback: () => void) => {
          if (!value || value > 10000000 || value < 1 || !Number.isInteger(Number(value))) {
            return callback(new Error('请输入1-10000000范围内的正整数'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
  };
  const StubimAddFrom = reactive({
    name: "",
    num: ""
  });

  async function CloseEntryPlatform(row: FormInstance | undefined) {
    row.resetFields()
    // ShowEchartsData()
    if (sessionStorage.getItem("seiId")) {
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
      }
      const params = qs.stringify({ sEid: sessionStorage.getItem("seiId") || '', })
      const res = await ProductInStockGetProductCategoryNums(params, data);
      if (!res.success) {
        ElMessage.error(res.msg)
        return
      } else {
        nextTick(() => {
          isShowChart(res.data)
        })
      }
    }
    AddVisible.value = false;
  }

  function SubtimEntryPlatform(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = qs.stringify({
        productName: StubimAddFrom.name,
        productQuantity: Number(StubimAddFrom.num),
        taskId: route.query.taskId,
        planId: route.query.planId,
        sEId: sessionStorage.getItem("seiId"),
      });
      const res = await ProductInStockCreate(data);
      if (res.success) {
        ElMessage.success('添加到货成功')
        CloseEntryPlatform(row);
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 获取产品名称
  async function GetProductInStockGetProductCategoriesName() {
    const res = await ProductInStockGetProductCategoriesName();
    if (res.success) {
      AddSelete.value = res.data;
    } else {
      ElMessage.error(res.msg)
    };
  }

  async function ShowEchartsData() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const params = qs.stringify({ sEid: sessionStorage.getItem("seiId") || '', })
    const res = await ProductInStockGetProductCategoryNums(params, data);
    if (!res.success) {
      ElMessage.error(res.msg)
      return
    } else {
      nextTick(() => {
        isShowChart(res.data)
      })
    }
  }


  function isShowChart(data) {
    const chartDom = document.getElementById('inventory');
    const myChart = echarts.init(chartDom);
    const datas = [
      {
        "productName": "键盘",
        "nums": 0
      },
      {
        "productName": "打印机",
        "nums": 0
      },
      {
        "productName": "鼠标",
        "nums": 0
      },
      {
        "productName": "智能手机",
        "nums": 0
      },
      {
        "productName": "笔记本电脑",
        "nums": 0
      },
      {
        "productName": "显示器",
        "nums": 0
      },
    ]
    data.forEach(item => {
      const foundItem = datas.find(a => item.productName == a.productName)
      if (foundItem) {
        foundItem.nums = item.nums
      }
    })
    console.log('data', data)
    console.log('datas', datas);

    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: (item) => {
          return `
            <p>${item[0].value.productName}</p>
            <p>数量：${item[0].value.nums}</p>
          `
        }
        // axisPointer: {
        //   type: 'shadow'
        // }
      },
      dataset: {
        dimensions: ['productName', 'nums'],
        source: datas
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: { type: 'category' },
      yAxis: { minInterval: 1 },
      series: [{ type: 'bar', }]
    };
    option && myChart.setOption(option);
    window.onresize = function () {
      myChart.resize();
    }
  }
  onMounted(() => {
    GetProductInStockGetProductCategoriesName()
    let seiId = sessionStorage.getItem("seiId")
    if (!!seiId) {
      nextTick(() => {
        ShowEchartsData()
      })
    } else {
      isShowChart([])
      ElMessage.warning('请先锁定供应商！')
    }

  })
  return {
    rules,
    columns,
    loading,
    dataList,
    columns2,
    loading2,
    dataList2,
    AddSelete,
    AddVisible,
    DialogVisible,
    StubimAddFrom,
    RefStubimAddFrom,
    CloseEntryPlatform,
    SubtimEntryPlatform,
  }
}
